package cn.buildoncloud.labor.workermanapplet.business.modules.controller;

import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.Result;
import cn.buildoncloud.labor.workermanapplet.util.AppletUtil;
import cn.buildoncloud.labor.workermanapplet.util.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件操作
 * Description: cn.buildoncloud.labor.workermanapplet.business.modules.controller
 * Created by CuiZibo on 2018/12/7 16:31
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Dao dao;

    @Value("${webSystemIP}")
    private String webSystemIP;

    /*@RequestMapping("/pageShowFile")
    public Object pageShowFile(HttpServletRequest request, HttpServletResponse response, @RequestParam("fid") String fid) {
        File file = null;
        String fileStr = "";
        try {
            Record fileUploadInfo = dao.fetch("sys_fileupload_info", Cnd.where("id", "=", fid));
            if (fileUploadInfo != null && fileUploadInfo.getString("server_path").startsWith("/home")) {
                file = new File(fileUploadInfo.getString("server_path"));
                fileStr = FileUtil.fileToBase64(file);
                return Result.success(Constant.API_OPERATION_SUCCESS, "data:image/jpeg;base64,"+fileStr);
            } else {
                return Result.error("服务器上没有id为" + fid + "的文件，请检查数据库图片路径！");
            }

        } catch (Exception e) {
            log.error("file/pageShowFile", e);
            return Result.error("图片转换失败");
        }
    }*/

    /**
     * 通过文件ID查询文件，该接口需要单独传输openId来检验
     * @param openId
     * @param response
     * @param fid
     */
    @RequestMapping("/pageShowFile")
    public void pageShowFile(@RequestParam("openId") String openId, HttpServletResponse response, @RequestParam("fid") String fid) {
        InputStream in = null;
        OutputStream out = null;
        try {
            Result result = AppletUtil.checkOpenId(openId, dao);
            if (result.getCode() == 1) {
                AppletUtil.returnJson(response, JSONObject.toJSONString(result));
                return;
            }
            Record fileUploadInfo = dao.fetch("sys_fileupload_info", Cnd.where("id", "=", fid));
            if (fileUploadInfo != null && fileUploadInfo.getString("server_path").startsWith("/home")) {
                response.reset();
                response.setHeader("Content-Disposition", "");
                response.setHeader("Pragma", "No-cache");
                response.setHeader("Cache-Control", "No-cache");
                response.setDateHeader("Expires", 0);
                // 创建读取文件的流
                in = new FileInputStream(fileUploadInfo.getString("server_path"));
                // 创建输出文件的流，也就是response的OutputStream
                out = response.getOutputStream();
                // 进行读取并写出，是以前学习io的模版代码
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            } else {
                log.error("服务器上没有id为" + fid + "的文件，请检查数据库图片路径！");
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception ex) {

            }
        }

    }

    /**
     * 上传临时图片
     * @param base64File
     * @return
     */
    @RequestMapping("/upLoadBase64Jpg")
    public Object upLoadBase64Jpg(@RequestParam String base64File){
        Map<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("imgStr", base64File);
//        Response response = Http.post2(webSystemIP + "/fileupload/base64toJpg", parameterMap, 1000 * 60);
//        Result result = Json.fromJson(Result.class, response.getContent());
        try{
            String result = HttpUtil.post(webSystemIP + "/fileupload/base64toJpg", parameterMap, 1000 * 60);
            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_NETWORK_ANOMALY);
        }
    }

}
